package org.shuma.goods.controller;


import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.shuma.goods.common.BaseResponse;
import org.shuma.goods.common.ErrorCode;
import org.shuma.goods.common.ResultUtils;
import org.shuma.goods.domain.DTO.QueryOperatorRecord;
import org.shuma.goods.domain.entity.OperationRecord;
import org.shuma.goods.exception.BusinessException;
import org.shuma.goods.service.OperationRecordService;
import org.shuma.user.facade.UserFacade;
import org.shuma.user.vo.UserVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
public class RecordController {

    @Resource
    private OperationRecordService operationRecordService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @SofaReference(interfaceType = UserFacade.class, uniqueId = "${service.user.unique.id}",
            binding = @SofaReferenceBinding(bindingType = "bolt"))
    private UserFacade userFacade;

    /**
     * 查询操作记录
     * @param queryOperatorRecord
     * @param userVo
     * @return
     */
    @GetMapping("/operator_record")
    public BaseResponse<Page<OperationRecord>> getRecord(@RequestBody QueryOperatorRecord queryOperatorRecord,
                                                         @RequestAttribute("userInfo")UserVo userVo) {
        if(queryOperatorRecord == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Long userId = userVo.getId();
        String redisKey = String.format("user:record:%s", userId);
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();

        //如果有缓存直接读取
        Page<OperationRecord> recordPage = (Page<OperationRecord>) operations.get(redisKey);
        if (recordPage != null) {

            return ResultUtils.success(recordPage);
        }

        //无缓存，查数据库
        recordPage = operationRecordService.listPageRecord(queryOperatorRecord,userId);

        //写缓存，30秒过期
        try {
            operations.set(redisKey, recordPage, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set  key error", e);
        }

        return ResultUtils.success(recordPage);
    }


}
